#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<queue>
#include<vector>
using namespace std;
unordered_map<int,unordered_map<int,unordered_map<int,int> > > mp;
struct st{
	int x,y,wait;
};
int ans,n,m,r,ti,d,pos,t,cnt;
int bfs(){
    unordered_map<int,unordered_map<int,unordered_map<int,int> > > md;
	queue<st> q;
	q.push({0,0,0});
	while(!q.empty()){
		st tt=q.front();
		q.pop();
		int x=tt.x,y=tt.y,wait=tt.wait,dlt=x+y+wait;
 		if(md[x][y][wait]) continue;
		md[x][y][wait]=1;
	 	if(x==n&&y==m) return n+m+wait;	
		if(mp[dlt+1][1][x]==0&&mp[dlt+1][2][y+1]==0){
			if(y+1<=m&&md[x][y+1][wait]==0){
			    q.push({x,y+1,wait});
			} 
		} 
		if(mp[dlt+1][1][x+1]==0&&mp[dlt+1][2][y]==0){
			if(x+1<=n&&md[x+1][y][wait]==0){
			    q.push({x+1,y,wait});
			} 
		} 
		if(mp[dlt+1][1][x]==0&&mp[dlt+1][2][y]==0){
		    if(wait+1<=r&&md[x][y][wait+1]==0){
		        q.push({x,y,wait+1});
		    }
		}
	}
	return -1;
} 
int main(){
	cin.tie(0),cout.tie(0);
	cin>>t;
	while(t--){
		cin>>n>>m>>r;
		for(int i=1;i<=r;i++){
			cin>>ti>>d>>pos;
			mp[ti][d][pos]=1;
		}
		cout<<bfs()<<endl;
		mp.clear();
	}
}
